<template>
  <div>
    <n-popover
      ref="popover"
      placement="bottom"
      trigger="click"
      :show-arrow="false"
      raw
      @update:show="updateShow"
    >
      <template #trigger>
        <div ref="input">
          <n-input
            v-model:value="pageData.search"
            type="text"
            @input="keyWordSearch"
            @focus="inputFocus"
          />
        </div>
      </template>
      <!-- v-loading="loading" -->
      <div class="select" ref="container" :style="computedStyle" @scroll="scroll">
        <div
          class="select-item"
          v-for="(item, index) in pageData.selectList"
          :key="index"
          :class="pageData.selectItemOn[labelField] == item[labelField] ? 'active' : ''"
          :style="{ width: pageData.inputWidth + 'px' }"
          @click="selectItem(item)"
        >
          {{ item[labelField] }}
        </div>
        <n-spin
          class="flex"
          style="justcify-content: center"
          size="small"
          v-if="isPage && total != pageData.sourese.length && isScroll"
        />
      </div>
    </n-popover>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch, nextTick, computed } from 'vue'
const container = ref(null) // 引用容器元素
const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: null
  },
  // 选项
  options: {
    type: Array,
    default: () => []
  },
  // label字段
  labelField: {
    type: String,
    default: null
  },
  // value字段
  valueField: {
    type: String,
    default: null
  },
  loading: {
    type: Boolean,
    defaut: false
  },
  // 是否分页
  isPage: {
    type: Boolean,
    defaut: false
  },
  // 开启分页传入total
  total: {
    type: Number,
    defaut: 0
  },
  // 是否需要滚动
  isScroll: {
    type: Boolean,
    defaut: false
  }
})
const emit = defineEmits(['update:modelValue', 'scrollBottom', 'select', 'keywordSearchList'])
const input = ref<any>()
const popover = ref() //弹出层ref
const pageData: any = reactive({
  search: null, //搜索内容
  selectItemOn: {} as any, //选择的
  sourese: [],
  selectList: [], //选择数据
  inputWidth: 0
})

watch(
  () => props.options,
  (newVal) => {
    setTimeout(() => {
      pageData.sourese = JSON.parse(JSON.stringify(newVal)) //原下拉选数据
      pageData.selectList = JSON.parse(JSON.stringify(newVal)) //下拉选数据
      if (newVal.length) {
        // 有默认值匹配选中的值
        let selectList = pageData.sourese.filter((item: any) => {
          return item[props.valueField] == pageData.search
        })
        if (selectList.length) {
          pageData.search = selectList[0][props.labelField]
          pageData.selectItemOn = selectList[0]
        }
      }
    }, 500)
  },
  { immediate: true, deep: true }
)
// 监听输入框值变化
watch(
  () => props.modelValue,
  (newVal, _oldVal) => {
    console.log(newVal, 'newVal', props.options)
    if (newVal && newVal != _oldVal) {
      pageData.search = newVal
    } else {
      pageData.search = null
    }
  },
  { immediate: true }
)
// 选择item
const selectItem = (item: any) => {
  nextTick(() => {
    // console.log(popover.value, 'popover.value');
    popover.value?.setShow(false)
    //
  })
  pageData.selectItemOn = item
  emit('update:modelValue', item[props.labelField])
  emit('select', item)
  pageData.search = item[props.labelField]
}
// 搜索
const keyWordSearch = (val: any) => {
  console.log('触发', val)
  popover.value?.setShow(true)
  emit('update:modelValue', val)
  pageData.selectItemOn = {}
  // 开启分页搜索keyword搜索
  if (props.isPage) {
    // 防抖触发
    emit('keywordSearchList', val)
  } else {
    if (val) {
      pageData.selectList = pageData.sourese.filter((item: any) => {
        return item[props.labelField].includes(val)
      })
    } else {
      pageData.selectList = pageData.sourese
    }
  }
}
const inputFocus = () => {
  pageData.selectList = pageData.sourese
}
const computedStyle = computed(() => {
  if (pageData.selectList.length != pageData.sourese.length) {
    if (pageData.selectList.length > 5) {
      return {
        height: `175px`,
        overflow: 'auto'
      }
    }
    return ''
  }
  if (pageData.sourese.length > 5) {
    return {
      height: `175px`,
      overflow: 'auto'
    }
  }
  return ''
})
//滚动到底部
const scroll = (e: Event) => {
  const target: Event | any = e.target
  // scrollTop 表示滚动条顶部距离容器顶部的垂直距离，
  // scrollHeight 表示容器的总高度，
  // clientHeight 表示可见区域的高度。
  if (target.scrollTop + target.clientHeight >= target.scrollHeight - 20) {
    if (props.isPage) {
      // 防抖触发
      emit('scrollBottom')
    }
  }
}
const updateShow = (val: any) => {
  if (val) {
    // 如果开启分页打开重新执行初始化请求
    if (props.isPage) {
      // 防抖触发
      emit('keywordSearchList', '')
    }
    // nextTick(() => {
    //   const observer = new IntersectionObserver((entries) => {
    //     entries.forEach((entry) => {
    //       console.log(entry, 'entries');
    //       if (entry.isIntersecting) {
    //         console.log(entry.target.textContent, '进入'); // 元素进入可视区域
    //       } else {
    //         console.log('离开', entry);
    //         // 元素离开可视区域
    //       }
    //     });
    //   });
    //   observer.observe(container.value);
    // });
  }
}
onMounted(() => {
  nextTick(() => {
    pageData.inputWidth = input.value.clientWidth
    console.log(input.value, 'input.value.clientWidth')
  })
})
</script>

<style lang="less" scoped>
.select {
  background: var(--qc-normal-background-color);
  padding: 5px;
  border-radius: 3px;
  position: relative;
}
.select-item {
  padding: 6px 5px;
  cursor: pointer;
}
.select-item:hover {
  background: #eee;
}
.active {
  background: #eee;
}
</style>
